package com.itheima;

import java.awt.*;

public class Shape {
    public static final int ROTATE = 0;
    public static final int LEFT = 1;
    public static final int RIGHT = 2;
    public static final int DOWN = 3;
    private int[][] body;
    private int status;
    private int left;
    private int top;

    public int getLeft() {
        return left;
    }

    public int getTop() {
        return top;
    }

    private ShapeListener shapeListener;

    public void setBody(int[][] body) {
        this.body = body;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void moveLeft() {
        System.out.println("shapes moveleft");
        left--;
    }

    public void moveRight() {
        System.out.println("shapes moveright");
        left++;
    }

    public void moveDown() {
        System.out.println("shapes moveDown");
        top++;
    }

    public void rotate() {
        System.out.println("shapes rotate");
        status = (status + 1) % body.length;
    }

    public void drawMe(Graphics g) {
        System.out.println("shapes drawMe");
        g.setColor(Color.red);
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                if (getFlagByPoint(status, x, y)) {
                    g.fill3DRect((left + x) * Global.CELL_SIZE, (y + top) * Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true);
                }
            }
        }
    }

    protected boolean getFlagByPoint(int status, int x, int y) {
        if (body != null) {
            return body[status][y * 4 + x] == 1;
        } else {
            return false;
        }
    }

    public boolean isMember(int x, int y, boolean isRotate) {
        return getFlagByPoint(isRotate ? (status + 1) % body.length : status, x, y);
    }

    private class ShapeDriver implements Runnable {

        @Override
        public void run() {
            //  shapeListener.isShapeMoveDownable(Shape.this)
            while (shapeListener.isShapeMoveDownable(Shape.this)) {
                moveDown();
                shapeListener.shapeMoveDown(Shape.this);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Shape() {
        new Thread(new ShapeDriver()).start();
    }

    public void addShapeListener(ShapeListener l) {
        if (l != null)
            this.shapeListener = l;
    }
}
